package com.zws.cucumber.wiremock.transformer;

import com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder;
import com.github.tomakehurst.wiremock.common.FileSource;
import com.github.tomakehurst.wiremock.extension.Parameters;
import com.github.tomakehurst.wiremock.extension.ResponseDefinitionTransformer;
import com.github.tomakehurst.wiremock.http.Request;
import com.github.tomakehurst.wiremock.http.ResponseDefinition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * author: zws
 */
public class ZwsStatusResponseTransformer extends ResponseDefinitionTransformer {

    private static final Logger logger = LoggerFactory.getLogger(ZwsStatusResponseTransformer.class);

    public static final String NAME = "response-status";

    @Override
    public ResponseDefinition transform(Request request, ResponseDefinition responseDefinition, FileSource files,
        Parameters parameters) {
        String status = responseDefinition.getTransformerParameters() != null
                            ? responseDefinition.getTransformerParameters().getString("response-status", null)
                            : null;
        if (status == null) {
            logger.info("not change status code");
            return responseDefinition;
        } else {
            logger.info("change status code to {}", status);
            ResponseDefinitionBuilder newResponseDefBuilder = ResponseDefinitionBuilder.like(responseDefinition);
            newResponseDefBuilder.withStatus(Integer.parseInt(status));
            return newResponseDefBuilder.build();
        }
    }

    @Override
    public String getName() {
        return NAME;
    }

    @Override
    public boolean applyGlobally() {
        return false;
    }
}
